﻿$(function() {
//Declare variable
var BranchCode = $( "#BranchCode" ),
		BranchName = $( "#BranchName" ),
		Address = $( "#Address" ),
		OpenDate= $("#OpenDate"),
		Tax= $("#Tax"),
		ContactName=$("#ContactName"),
		ContactTele=$("#ContactTele"),
		ContactEmail=$("#ContactEmail"),
		Telephone=$("#Telephone"),
		allFields = $( [] ).add( BranchCode )
							.add(BranchName)
							.add(Tax)
							.add(Address)
							.add(OpenDate)
							.add(ContactName)
							.add(ContactTele)
							.add(ContactEmail)
							.add(Telephone)	,
		tips = $( ".validateTips" ),
		button_name="",
		url="a_branch.php", 
		branchID="",
		rowSelect="";
		
		
		//Set DateTime to control
		$( "#OpenDate" ).datepicker({ dateFormat: 'dd/mm/yy',
						showOn: "button",
						buttonImage: "images/Calendar.png",
						buttonImageOnly: true });
		
		 //Load First page
		 LoadData(1,true);
 
	
		//Show Loading bar			
		function showLoader(){
			$( "#resultData tbody:first" ).prepend( "<tr>"
						+"<td colspan='10' class='search-background'>"
						+"<label><img src='./images/ajax-loader.gif'/></label>"
						+"</td>"
						+"</tr>" ); 
			 $('.search-background').fadeIn(900,0);
		}
		//Hide Loading bar			
		function hideLoader(){
			$('.search-background').fadeOut(300);
			$( "#resultData tbody tr" ).remove();
		};
		
		function updateTips( t ) {
			tips
				.text( t )
				.addClass( "ui-state-highlight" );
			setTimeout(function() {
				tips.removeClass( "ui-state-highlight", 1500 );
			}, 500 );
		}

		function checkInputFile( o, n, min ) {
			if (o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Please input " + n + "." );
				return false;
			} else {
				return true;
			}
		}
		function AddErrorMessage(o,n){
			o.addClass( "ui-state-error" );
			updateTips( n );
			return false;
		}
		function checkLength( o, n, min, max ) {
			if ( o.val().length > max || o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Length of " + n + " must be between " +
					min + " and " + max + "." );
				return false;
			} else {
				return true;
			}
		}

		function checkRegexp( o, regexp, n ) {
			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass( "ui-state-error" );
				updateTips( n );
				return false;
			} else {
				return true;
			}
		}
					
		function getData(id){
			var dataSet={'id':id,'m':'detail'}; 
			$.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: dataSet,		
				success: function(data){
					var obj=eval('(' + data + ')'); 
				  	for (value in obj){
						txt="#"+value;
						//alert(value);
						if (value=="OpenedDate"){
							$("#OpenDate").datepicker("setDate" , obj[value]) ;
						}else if (value=="Type"){
							 
							 $("[name=Type]").filter("[value="+obj[value]+"]").attr("checked","checked");
						}else{
							$(txt).val(obj[value]);
						}	

						if ($("#mode" ).val()=="view")
							$(txt).attr("readonly","true");
					}
				
				 },//e.responseText
				 error:function(jqXHR, textStatus, errorThrown) { alert(jqXHR+":"+textStatus); }
				// complete:function() { alert("complete"); }
			});
		}
		
		function callAjax(obj,id){
			var m=$("#mode").val();
			var rows=$("#rowCount").attr('innerHTML');
			
			if (m=='edit'){
				rows=rowSelect.find("td").eq(0).html();
			}
			$.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: {"m":m,"var":obj,"id":id,"rows":rows},
				success: function(data){
					//alert(data);
					if (m=='add'){
						if (data=='error'){
							AddErrorMessage(BranchCode,BranchCode.val() + ' already exists' );
						}else{
							if (rows=="0"){
								$( "#resultData tbody tr").remove();
							}
							//Insert data to first row.
							$( "#resultData tbody:first" ).prepend( data ); 
							//Set font color
							$( "#resultData tbody tr:first" ).css('color','blue');
							//Plus row number ;
							//var rows=$("#rowCount").attr('innerHTML');
							$("#rowCount").attr('innerHTML',parseInt(rows,10)+1)
							//Close
							$( "#dialog-form" ).dialog( "close" );
						}
					}else if (m=='edit'){
						if (data=='error'){
							AddErrorMessage(BranchCode,BranchCode.val() + ' already exists' );
						}else  {
							rowSelect.html(data);
							//CLose 
							$( "#dialog-form" ).dialog( "close" );
						}
					}
				}
			});
		}
		//Close Dialog
		$( "#dialog:ui-dialog" ).dialog( "destroy" );
		
		//Confirm Dialog
		$( "#dialog-confirm" ).dialog({
			resizable: false,
			height:160,
			zIndex:9999,
			autoOpen: false,
			modal: true
		});
		
		//Form Edit Add 
		$( "#dialog-form" ).dialog({
			autoOpen: false,
			resizable:false,
			height: 480,
			width: 450,
			zIndex:9999,
			modal: true,
			open: function() {
				tips.text( "* fields are required." );
				if ($("#mode" ).val() =="edit" || $("#mode" ).val()=="view"){
					getData(branchID);
				}else{
					allFields.val( "" );
				}
			},
			close: function() {
				allFields.attr("readonly","");
				allFields.val( "" ).removeClass( "ui-state-error" );
			}
		});
		// Set value from control to array 
		function getValue(){
			var o = {};
			//get name and value control 
			$( "#dialog-form" ).find('input').each(function(){
				if (o[$(this).attr('id')]) {
					if (!o[$(this).attr('id')].push) {
						o[$(this).attr('id')] = [o[$(this).attr('id')]];
					}
					o[$(this).attr('id')].push($(this).val() || '');
				} else {
					o[$(this).attr('id')] = $(this).val() || '';
				}
			});
			o['Type']=$('input[name=Type]:checked').val();
			//Address 
			var _address = $( "#dialog-form" ).find('textarea').eq(0);
			o[_address.attr('id')] = _address.val() || '';
			
			return o;
		}
		// Check input data in control
		function checkRequireControl(){
			var bValid=true;
			bValid = bValid && checkInputFile( BranchCode, "Branch Code",1);
			bValid = bValid && checkInputFile( BranchName, "Branch Name",1 );
			bValid = bValid && checkInputFile( Tax, "Tax",1 );
			bValid = bValid && checkInputFile( Address, "Address", 1 );
			bValid = bValid && checkInputFile( OpenDate, "Opend Date", 5 );
			bValid = bValid && checkInputFile( ContactName, "Contact Name", 1 );
			bValid = bValid && checkInputFile( ContactTele, "Contact Tele", 1 );
			//bValid = bValid && checkRegexp( ContactTele, /^([0-9])+$/, "Telephone field only allow : 0-9" );
			//bValid = bValid && checkInputFile( ContactEmail, "Email", 1 );
			bValid = bValid && checkRegexp( ContactEmail, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. admin@oriental.com" );					
			return bValid;
		}
		
		//Add Button
		$( "#btnAdd" ).live('click',function() {
			//set mode
			$("#mode").val("add");
			//set title
			$("#dialog-form").dialog({'title':'Create new Branch'});
			$( "#dialog-form" ).dialog( "open" );
			$( "#dialog-form" ).dialog( "option","buttons",{
				"Create Branch":function(){
					allFields.removeClass( "ui-state-error" );
					if ( checkRequireControl() ) {
						callAjax(getValue(),0); // call ajax function for add new data
					//	$( this ).dialog( "close" );
					
					}else{
						return false;
					}
				},
				"Cancel":function(){$( this ).dialog( "close" );}
			});
			
			return false
		});
			
		// Edit Click
		$(".btnEdit").live('click',function() {
			$("#mode").val("edit"),
			rowSelect=$(this).parent().parent(),
			branchID=$(this).parent().parent().find("td").eq(1).html(),
			getData(branchID),
			$("#dialog-form").dialog({'title':'Update Branch'});
			$("#dialog-form").dialog("open");
			$("#dialog-form").dialog( "option","buttons",{
				"Update":function(){
					var bValid = true;
					allFields.removeClass( "ui-state-error" );
					if ( checkRequireControl() ) {
						callAjax(getValue(),branchID); // call ajax for update 
						$( this ).dialog( "close" );
					}
				}
				,"Cancel":function(){
					$( this ).dialog( "close" );
				}
			}
			);
			return false;	
		});
			
		//Delete Click
		$(".btnDel").live('click',function(){
			var tableRow  = $(this).parent().parent().parent();
			rowSelect = $(this).parent().parent();
			branchID=$(this).parent().parent().find("td").eq(1).html();
			var irow=$(this).parent().parent().find("td").eq(0).html();
			
			$("#mode").val("del");
			$("#dialog-confirm").dialog("open");
			$("#dialog-confirm").dialog("option","buttons",	{
				"Delete": function() {
					callAjax({"id":branchID}); 	//Call Ajax delete data
					rowSelect.remove(); // remove row
					//
					tableRow.find("tr").each(function(){
						if (irow < parseInt($(this).find("td").eq(0).html()))
							$(this).find("td").eq(0).html( parseInt($(this).find("td").eq(0).html()) - 1 );	
					});	
					
					var rows=$("#rowCount").attr('innerHTML');
					$("#rowCount").attr('innerHTML',parseInt(rows,10)-1);
					
					$( this ).dialog( "close" );
				},
				Cancel: function() {
						$( this ).dialog( "close" );
				}
			});
		});
			
		// View Click
		$(".btnView").live('click', function(){
			$("#mode").val("view");
			//get Branch ID
			branchID=$(this).parent().parent().find("td").eq(1).html();
			//Load Detail
			getData(branchID); 
			allFields.val( "" ).removeClass( "ui-state-error" ),
			$( ".validateTips" ).html(''),
			$("#dialog-form").dialog({'title':'View Branch'}),
			$("#dialog-form").dialog("open"),
			$("#dialog-form").dialog("option","buttons",{
				"Close":function(){
					allFields.attr("readonly","");
					$( this ).dialog( "close" );
					}
				});
		});
		
		// Search Click
		$("#btnSearch").click(function(){
			LoadData(1,true);
		});
		//b=false , don't gennerate paging
		function LoadData(page,b){
			$( "#resultData tbody tr" ).remove();
			//Show loading
			showLoader();
			//set criteria
			var dataSet={'m':'search'
						,'code':$("#txtBranchCode_s").val()
						,'name':$("#txtBranchName_s").val()
						,'page':page
						};  
			 //Post 			
			 $.post(url,  dataSet , function(data){
				// alert(data);
				//hide loading
				hideLoader();
				//convert string json to java json
				var obj=eval("(" + data + ")");
				//set data to table
				$( "#resultData tbody" ).append(obj['data']);
				//set row 
				$("#rowCount").attr('innerHTML',obj['rows']);
				//set page
				if (b){
					// var p="<ul>";
					// for (var i=parseInt(obj['totalpage']);i >0 ;i--){
						// p = p +'<li id="'+i+'">'+i+'</li>';
					// }
					// p = p+"</ul>";
					// $("#paging_button ul").remove();
					// $("#paging_button").append(p);
					if (parseInt(obj['totalpage'])>1){
						$("#paging_btn").show();
						setPaging(parseInt(obj['totalpage']));
					}else{
						$("#paging_btn").hide();
					}					
					 
				}
				//$("#"+page).css({'background-color' : '#006699'});
			 });
		}
 
			
	// $("#paging_button li").live('click',function(){
		// $("#paging_button li").css({'background-color' : ''});
 		// LoadData(this.id,false);

	// });
	function setPaging(iTotal){
				 $("#paging_btn").paginate({
				count 		: iTotal,
				start 		: 1,
				display     : 10,
				border					: false,
				text_color  			: '#888',
				background_color    	: '#EEE',	
				text_hover_color  		: 'blue',
				background_hover_color	: '#CFCFCF',
				mouse					: 'press',
				onChange     			: function(page){
											LoadData(page,false);
										  }
			});
		}
});
	